﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Truextend.Training.Service;
using Truextend.Training.Model.Entities;
using Truextend.Training.Business;
using Truextend.Training.Business.Interfaces;
using Truextend.Training.Business.Dtos;
using Microsoft.SharePoint;

namespace Truextend.Training.Service
{
    public class UserCourseService : BaseService
    {
        public UserCourse AddUserCourse(UserCourse userCourse, long courseInstanceId)
        {
            ExecuteManager(uow =>
            {
                IUserCourseManager manager = new UserCourseManager(uow);
                ICourseInstanceManager managerInstance = new CourseInstanceManager(uow);

                CourseInstance courseInstance = managerInstance.GetCourseInstanceById(courseInstanceId);
                userCourse.CourseInstanceReference.EntityKey = courseInstance.EntityKey;
                
                userCourse = manager.AddUserCourse(userCourse);
            });
            return userCourse;
        }

        public IList<UserCourse> GetAllUserCourses(int userId)
        {
            IList<UserCourse> result = null;
            ExecuteManager(uow =>
            {
                IUserCourseManager manager = new UserCourseManager(uow);
                result = manager.GetAllUserCourses(userId);
            });
            return result;
        }

        public IList<InstanceUserCourseDto> GetInstanceUserCourse(SPSite site)
        {
            IList<InstanceUserCourseDto> users = new List<InstanceUserCourseDto>();
            IList<CourseInstance> courseInstances = null;
            IList<UserCourse> userCourses = null;

            SPWeb web = site.OpenWeb();

            ExecuteManager(uow =>
                {
                    ICourseInstanceManager managerInstance = new CourseInstanceManager(uow);
                    courseInstances = managerInstance.GetInstancesOneDayBeforeStart();

                    IUserCourseManager managerUserCourse = new UserCourseManager(uow);
                    userCourses = managerUserCourse.GetInstanceUsers();

                    foreach (UserCourse uc in userCourses)
                    {
                        SPUser user = web.AllUsers.GetByID(uc.UserId);
                        SPUser instructor = web.AllUsers.GetByID(uc.CourseInstance.InstructorId);
                        InstanceUserCourseDto iuc = new InstanceUserCourseDto
                        {
                            UserID = uc.UserId,
                            UserName = user.Name,
                            UserEmail = user.Email,
                            CourseName = "Course1",
                            InstructorName = instructor.Name
                            
                        };

                        users.Add(iuc);
                    }
                });

            return users;
        }

    }
}
